package com.by.basicweb.jsonserializer;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.by.toolkit.consts.DatePatternConst;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 反序列化LocalDateTime
 *
 * @author YanBingHao
 * @since 2023/12/29
 */
public class LocalDateTimeJsonToDBUnixTimeDeserializer extends JsonDeserializer<Long> {

    @Override
    public Long deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {

        if (Objects.nonNull(p) && StringUtils.isNotBlank(p.getText())) {
            LocalDateTime localDateTime = LocalDateTimeUtil.parse(p.getText(), DatePatternConst.DATE_TIME_PATTERN);
            return LocalDateTimeUtil.toEpochMilli(localDateTime) / 1000;
        }

        return null;    }
}
